import axios from 'axios'
import { createBrowserHistory } from 'history'
import { getToken } from './index'
import { message } from 'antd'

const history = createBrowserHistory()
const request = axios.create({
  baseURL: '/hala',
  // timeout: 5000
})

// 定义全局loading开关
let loading = false

// 添加拦截器
// 请求拦截
request.interceptors.request.use(function (config) {
  loading = true
  // 请求头中携带token
  if (getToken()) {
    config.headers.token = getToken()
  }
  return config;
}, function (error) {
  loading = false
  return Promise.reject(error);
});
// 响应拦截
request.interceptors.response.use(function (response) {
  loading = false
  const errCode = [401, 403]
  if (errCode.includes(response.data.code)) {
    message.error('token过期了，请重新登录', 2, () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userinfo')
      history.go(0)
    })
  }
  return response;
}, function (error) {
  loading = false
  return Promise.reject(error);
});

export {
  request,
  loading
}